package edu.washington.cs.sounddetector.server.api.methodlogic;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;

import org.apache.commons.lang3.Validate;

import edu.washington.cs.sounddetector.server.c2dm.C2DMessaging;
import edu.washington.cs.sounddetector.server.c2dm.RegistrationIdRemover;
import edu.washington.cs.sounddetector.server.database.ReceiverPhone;

/**
 * Implements logic for removing registration ids in certain error cases of the {@link C2DMessaging}
 * push notification sender.
 * 
 * @author the.dylan.price@gmail.com
 * 
 */
public class RegistrationIdRemoverImpl implements RegistrationIdRemover
{

    private PersistenceManagerFactory pmf;

    public RegistrationIdRemoverImpl(PersistenceManagerFactory pmf)
    {
        Validate.notNull(pmf);

        this.pmf = pmf;
    }

    @Override
    public void removeRegistrationId(String registrationId)
    {
        PersistenceManager pm = pmf.getPersistenceManager();
        Transaction tx = pm.currentTransaction();
        try
        {
            tx.begin();
            Query query = pm.newNamedQuery(ReceiverPhone.class, ReceiverPhone.QUERY_BY_REGID);
            query.setUnique(true);
            ReceiverPhone phone = (ReceiverPhone) query.execute(registrationId);
            phone.setRegistrationId(null);
            pm.makePersistent(phone);
            tx.commit();
        }
        finally
        {
            if (tx.isActive())
                tx.rollback();
            pm.close();
        }
    }

}
